package com.zmc.order.infrastructure.updater.order;

import com.alibaba.fastjson.JSON;
import com.zmc.order.exception.OrderException;
import com.zmc.order.infrastructure.entity.OrderEntity;
import com.zmc.order.infrastructure.enums.OrderEnum;
import com.zmc.order.infrastructure.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author：zmc
 * @Date：2025/5/15 18:04
 * 订单确认收货
 */
@Component
public class OrderConfirmReceiveUpdater<T> implements OderUpdater<T> {

    public static Logger log = LoggerFactory.getLogger(OrderConfirmReceiveUpdater.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private CommentMemberInfoService commentMemberInfoService;

    @Override
    @Transactional
    public void execute(T param) {
        String orderSn = (String) param;
        OrderEntity order = orderService.getByOrderSn(orderSn);
        if (order == null) {
            log.error("订单确认收货异常：orderSn:{} 不存在", orderSn);
            throw new OrderException("订单不存在");
        }
        if (OrderEnum.ORDER_STATUS_HAS_SEND_GOOD.getCode() != order.getStatus()) {
            log.error("订单确认收货异常：order:{}", JSON.toJSONString(order));
            throw new OrderException("订单状态异常,无法确认收货");
        }
        //更新订单状态为待评价
        orderService.updateOrderWhenReceive(orderSn, OrderEnum.ORDER_STATUS_COMPLETE.getCode(), 1);
        //同步更新商户订单
        merchantOrderService.updateStatus(order.getMerchantOrderSn(), OrderEnum.ORDER_STATUS_COMPLETE.getCode());
        //创建用户待评论列表
        String spuId = orderItemService.listByOrderSn(orderSn).stream().findFirst().orElseThrow(() -> new OrderException("获取订单类目异常")).getSpuId();
        commentMemberInfoService.initCommentMemberInfo(order.getMemberId(), order.getOrderSn(), spuId);
    }
}
